package com.summer.safe.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.summer.safe.base.BaseController;
import com.summer.safe.base.TreeNode;
import com.summer.safe.config.annotation.ResultWrapper;
import com.summer.safe.config.properties.ConfigureProperties;
import com.summer.safe.config.result.ResultCode;
import com.summer.safe.system.entity.Menu;
import com.summer.safe.system.service.SystemService;
import com.summer.safe.utils.*;
import com.summer.safe.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 *
 * 菜单
 */

@Controller
@RequestMapping("/sys/menu")
public class MenuController extends BaseController {

    private String PREFIX = "/system/menu/";
    @Autowired
    private SystemService systemService;

    @Resource
    private ConfigureProperties configureProperties;


    @ModelAttribute("menu")
    public Menu get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return systemService.getMenu(id);
        } else {
            return new Menu();
        }
    }

    @RequiresPermissions("sys:menu:view")
    @GetMapping
     public String list() {
        return PREFIX + "menulist.html";
    }

    @GetMapping("/dataList")
    @ResultWrapper(ResultCode.SUCCESS_QUERY)
    public JsonResult dataList(Model model, Menu menu) {
        List<Menu> list = systemService.findAllMenu();
        return JsonResult.success(list);
    }

    @GetMapping("/menuData")
    @ResultWrapper
    public List<Menu> dataLista(Model model,Menu menu) {
        List<Menu> list = systemService.findAllMenu();
        return list;
    }


    @RequiresPermissions("sys:menu:edit")
    @GetMapping("/form")
    public String form(Menu menu, Model model) {
        if(menu.getOp().equals(Global.OP_ADD)){
            if (menu.getParent() == null || menu.getParent().getId() == null){
                menu.setParent(new Menu(Menu.getRootId()));
            }
            menu.setParent(systemService.getMenu(menu.getParent().getId()));
            // 获取排序号，最末节点排序号+20
            if (StringUtils.isBlank(menu.getId())) {
                List<Menu> list = Lists.newArrayList();
                List<Menu> sourcelist = systemService.findAllMenu();
                Menu.sortList(list, sourcelist, menu.getParentId(), false);
                if (list.size() > 0) {
                    menu.setSort(list.get(list.size() - 1).getSort() + 20);
                }
            }
        }
        model.addAttribute("menu", menu);
        return PREFIX + "menuform.html";
    }



    @RequestMapping("updateSort")
    @ResponseBody
    public String updateSort(@RequestParam(value = "ids[]") String[] ids, @RequestParam(value = "sorts[]") Integer[] sorts) {
        for (int i = 0; i < ids.length; i++) {
            Menu menu = new Menu(ids[i]);
            menu.setSort(sorts[i]);
            systemService.updateMenuSort(menu);
        }
        return "success";
    }



    @PostMapping("/delete")
    @ResultWrapper(ResultCode.SUCCESS_DELETE)
    public void delete(Menu menu) {
        systemService.deleteMenu(menu);
        // 清除权限缓存
        ShiroUtils.clearCachedAuthorizationInfo();
    }



    @GetMapping(value = "treeData")
    @ResponseBody
    public List<TreeNode> treeData(@RequestParam(required = false) String extId, @RequestParam(required = false) String isShowHide, HttpServletResponse response) {
        List<Menu> list = systemService.findAllMenu();
        List<TreeNode> treeNodes = Lists.newArrayList();
        for (int i = 0; i < list.size(); i++) {
            Menu o = list.get(i);
            if (isShowHide != null && isShowHide.equals(Global.SHOW) && o.getIsShow().equals(Global.SHOW)) {
                continue;
            }
            TreeNode treeNode = new TreeNode();
            treeNode.setId(o.getId());
            treeNode.setpId(o.getParentId());
            treeNode.setName(o.getName());
            treeNodes.add(treeNode);
        }
        return treeNodes;
    }

    @RequestMapping(value = "save")
    @ResultWrapper(ResultCode.SUCCESS_SAVE)
    public void save(Menu menu) {
        //判断是否为演示模式
        ToolUtil.DemoMode();
        systemService.saveMenu(menu);
       // 清除权限缓存
        ShiroUtils.clearCachedAuthorizationInfo();
    }

    @RequestMapping(value = "jsonList",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String jsonList() {
        JSONObject jsonObject = new JSONObject();
        List<Menu> menus = systemService.findAllMenu();
        menus.forEach(menu -> {
            if (menu.getParentId().equals("1")) {
                JSONArray jsonArray = new JSONArray();
                jsonArray = getMenu(menus, jsonArray, menu.getId());
                jsonObject.put(menu.getId(), jsonArray);
            }
        });

        return JSON.toJSONString(jsonObject);
    }



    /**
     * 生成菜单栏
     */

   /* @ResponseBody
    @RequestMapping(value = "generate",produces = {"application/json;charset=UTF-8"})
    public JSONArray  generate () {

        List<Menu> menuList = UserUtils.getMenuList().stream().filter(menu -> "1".equals(menu.getIsShow())).collect(Collectors.toList());
        JSONArray jsonArray = new JSONArray();
        jsonArray = getMenu(menuList, jsonArray, "1");
        return jsonArray;
    }*/


    /**
     * 生成菜单栏
     */

    @ResponseBody
    @RequestMapping(value = "generate",produces = {"application/json;charset=UTF-8"})
    public Map<String, Object> generate () {

        List<Menu> menuList = UserUtils.getMenuList().stream().filter(menu -> menu.getIsShow().equals(Global.SHOW)).collect(Collectors.toList());
        JSONArray jsonArray = new JSONArray();

        Map<String, Object> map = new HashMap<>(16);
        Map<String,Object> home = new HashMap<>(16);
        Map<String,Object> logo = new HashMap<>(16);
        menuList.forEach(menu -> {
            JSONObject jsonObject = new JSONObject();
            //主页配置
            if(menu.getParentId().equals("0")){
                jsonObject.put("title", "主页");
                jsonObject.put("href", "/index/main");
                jsonObject.put("icon", "fa fa-home");
                jsonObject.put("target", "_self");
                jsonArray.add(jsonObject);
            }
            if (menu.getParentId().equals("1")) {

                jsonObject.put("title", menu.getName());
                jsonObject.put("href", menu.getHref());
                jsonObject.put("icon", menu.getIcon());
                jsonObject.put("target", "_self");
                JSONArray ja = new JSONArray();
                ja = getMenu(menuList, ja, menu.getId());
                if (ja.size() > 0) {
                    jsonObject.put("child", ja);
                }
                jsonArray.add(jsonObject);
            }
        });

        home.put("title","首页");
        home.put("href","/index/main");//控制器路由,自行定义
        //系统名称
        logo.put("title",configureProperties.getProductName());
        logo.put("image","/static/images/logo.png");
        map.put("homeInfo", home);
        map.put("logoInfo", logo);


        map.put("menuInfo", jsonArray);
        return map;
    }


    private JSONArray getMenu(List<Menu> menuList, JSONArray jsonArray, String key) {
        menuList.forEach(menu -> {
            if (menu.getParentId().equals(key)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("title", menu.getName());
                jsonObject.put("href", menu.getHref());
                jsonObject.put("icon", menu.getIcon());
                jsonObject.put("target", "_self");
                JSONArray ja = new JSONArray();
                ja = getMenu(menuList, ja, menu.getId());
                if (ja.size() > 0) {
                    jsonObject.put("child", ja);
                }
                jsonArray.add(jsonObject);
            }
        });
        return jsonArray;
    }



}
